package com.wlj.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wlj.security.core.support.SimpleResponse;
import com.wlj.security.core.properties.LoginType;
import com.wlj.security.core.properties.WljSecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("wljAuthenticationFailureHandler")
public class WljAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {


    private Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private WljSecurityProperties wljSecurityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException, ServletException {
        logger.info("登录失败");
        if(LoginType.JSON.equals(wljSecurityProperties.getBrowser().getLoginType())){
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(e.getMessage())));

        }else{
            //跳转到默认的错误展示页
            super.onAuthenticationFailure(request, response, e);
        }

    }
}
